from models import Library, db
from common.response import Response

from util.jsonUtil import library2dict , dict2library,response2dict

#获取全部个人图书馆
def getAllLibraryList():
    libraryList = Library.query.all()
    code = "200"
    msg = "查询成功"
    data = [library2dict(library) for library in libraryList]
    response = Response(code, msg, data)
    return response2dict(response)

#获取个人图书馆所有书籍
def getLibraryByUserID(userid):
    library = Library.query.filter_by(user_id=userid).first()

    if library:
        code = "200"
        msg = '获取成功'
        response = Response(code, msg, library2dict(library))
    else:
        code = "404"
        msg = '获取失败，没有该userid的用户'
        data= ''
        response = Response(code, msg,data)
    return response2dict(response)

#添加新个人图书馆
def addNewLibrary(library):
    oldlibrary = Library.query.filter_by(user_id=library.user_id)
    if oldlibrary:
        oldlibrary_1 = Library.query.filter_by(library_name = library.library_name).first()
        if oldlibrary_1:
            oldlibrary_1.num += library.num
            code = "200"
            msg = '添加成功'
            response = Response(code, msg, library2dict(library))
            db.session.commit()
            return response2dict(response)
        else:
            db.session.add(library)
            db.session.commit()
            code = "200"
            msg = '添加成功'
            response = Response(code, msg, library2dict(library))
            return response2dict(response)
    else:
        db.session.add(library)
        db.session.commit()
        code = "200"
        msg = '添加成功'
        response = Response(code, msg, library2dict(oldlibrary))
        return response2dict(response)

#更新个人图书馆信息
def updateLibrary(userid, library):
    oldLibrary = Library.query.filter_by(user_id=userid).first()
    oldLibrary.library_name = library.library_name
    oldLibrary.author = library.author
    oldLibrary.information = library.information
    oldLibrary.picture = library.picture
    oldLibrary.num = library.num
    oldLibrary.price = library.price
    oldLibrary.user_id = library.user_id
    oldLibrary.user_name = library.user_name

    db.session.commit()
    code = "200"
    msg = "更新成功"
    data = library2dict(oldLibrary)
    response = Response(code, msg, data)

    return response2dict(response)

#删除图书
def deleteLibrary(library_name):
    library = Library.query.get(library_name)
    db.session.delete(library)
    db.session.commit()
    code = "200"
    msg = "删除成功"
    data = library2dict(library)
    response = Response(code, msg, data)
    return response2dict(response)